package com.XinYun.Library.modules.admin.borrowMsg.service;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.XinYun.Library.modules.admin.borrowMsg.dao.BorrowMsgDao;
import com.XinYun.Library.modules.admin.borrowMsg.entity.BorrowMsg;
import com.XinYun.Library.modules.admin.borrowMsg.entity.BorrowPrintMsg;
import com.XinYun.Library.modules.admin.common.AdminReturnCode;
import com.XinYun.Library.modules.admin.common.BasicService;
import com.XinYun.Library.modules.admin.common.JSON.AdminJSON;
import com.XinYun.Library.modules.admin.common.SqlMapper;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;


public class BorrowMsgService extends BasicService {
    private BorrowMsgDao borrowMsgDao = new BorrowMsgDao();

    public List<BorrowMsg> getMsg(AdminJSON json, JSONObject jsonObj){
        //针对性解参
        String pageSize = jsonObj.get("pageSize", String.class);
        String pageIndex = jsonObj.get("pageIndex", String.class);
        String searchBy = jsonObj.get("searchBy", String.class);
        String keyWord = jsonObj.get("keyWord", String.class);
        String state = jsonObj.get("state", String.class);
        //客制化校验格式
        if(StrUtil.hasEmpty(pageSize,pageIndex))
            {setMsgCode(json, AdminReturnCode.ERR_EMPTY_PARAM);}
        else if(!(Validator.isNumber(pageSize) && Validator.isNumber(pageIndex)))
            {setMsgCode(json, AdminReturnCode.ERR_WRONG_PARAM);}
        else {
            //无错解析为数字继续
            Integer pagesize = Integer.valueOf(pageSize);
            Integer pageindex = Integer.valueOf(pageIndex);
            //是否搜索处理
            String isSearch = null;
            //不为空
            if(!StrUtil.hasEmpty(searchBy,keyWord)){
                keyWord = fuzzy(keyWord);
                //特殊情况处理--借阅查询下是否有serachBy
                if(!("借阅".equals(state) && !List.of("bookname","bid").contains(searchBy))){}
                    isSearch = " AND " +searchBy+ " LIKE " + "'"+keyWord+"'";
            }
            //分发获取数据和数据量
            List<BorrowMsg> borrowMsgs = new ArrayList<>();
            long dataNum = 0;
            switch (state){
                case "存留" : borrowMsgs = getSavedMsg(pagesize,pageindex,isSearch);
                dataNum = getSavedMsgNum(isSearch);break;
                case "被借阅" : borrowMsgs = getLoanedMsg(pagesize,pageindex,isSearch);
                dataNum = getLoanedMsgNum(isSearch);break;
                case "被逾期" : borrowMsgs = getOuttimeMsg(pagesize,pageindex,isSearch);
                dataNum = getOuttimeMsgNum(isSearch);break;
                default : throw new RuntimeException("NoSuchState");
            };
            //截断以用于导出excel
            if(json == null){
                return borrowMsgs;
            }
            //结果判断
            if(borrowMsgs.isEmpty() || dataNum == 0)
                {setMsgCode(json, AdminReturnCode.ERR_REQUEST_OVERRIDE);}
            else {
                //转换为前端易读结果
                List<BorrowPrintMsg> borrowPrintMsgs = new ArrayList<>();
                for (BorrowMsg msg : borrowMsgs) {
                    borrowPrintMsgs.add(parseToPrint(msg));
                }
                setMsgCode(json, AdminReturnCode.SUCCECSS);
                json.setData(borrowPrintMsgs);
                json.setDataNum(dataNum);
            }
        }
        return null;
    }

    public void getExcel(HttpServletResponse resp,  JSONObject jsonObj) throws IOException {
        //重复利用
        List<BorrowMsg> msg = getMsg(null,jsonObj);
        Object[] msgArr =  msg.toArray();
        //调用工具类输出列表为excel到servlet
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(msg, true);
        resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        resp.setHeader("Content-Disposition","attachment;filename=test.xlsx");
        //输出表格
        ServletOutputStream os = resp.getOutputStream();
        writer.flush(os, true);
        writer.close();
        IoUtil.close(os);
    }
    /**
     * 获得保留的书信息
     */
    private List<BorrowMsg> getSavedMsg(int pagesize, int pageindex,String isSearch){
        return borrowMsgDao.sqlPageFactory(SqlMapper.GET_SAVED_MSG,pagesize,pageindex,isSearch);
    }

    /**
     * 获得借阅的条目信息
     */
    private List<BorrowMsg> getLoanedMsg(int pagesize, int pageindex,String isSearch){
        return borrowMsgDao.sqlPageFactory(SqlMapper.GET_LOANED_MSG,pagesize,pageindex,isSearch);
    }

    /**
     * 获得逾期的条目信息
     */
    private List<BorrowMsg> getOuttimeMsg(int pagesize, int pageindex,String isSearch){
        return borrowMsgDao.sqlPageFactory(SqlMapper.GET_OUTTIME_MSG,pagesize,pageindex,isSearch);
    }

    /**
     * 获得保留的书信息
     */
    private long getSavedMsgNum(String isSearch){
        return borrowMsgDao.getDataNum(SqlMapper.GET_SAVED_MSG_NUM,isSearch);
    }

    /**
     * 获得借阅的条目信息
     */
    private long getLoanedMsgNum(String isSearch){
        return borrowMsgDao.getDataNum(SqlMapper.GET_LOANED_MSG_NUM,isSearch);
    }

    /**
     * 获得逾期的条目信息
     */
    private long getOuttimeMsgNum(String isSearch){
        return borrowMsgDao.getDataNum(SqlMapper.GET_OUTTIME_MSG_NUM,isSearch);
    }

    private BorrowPrintMsg parseToPrint(BorrowMsg book){
        //转值
        String starttime =  null;
        String endtime =  null;
        //处理
        Date Tempt1 = book.getStarttime();
        Date Tempt2 = book.getEndtime();
        if(Tempt1 != null && Tempt2 != null){
            starttime = Tempt1.toString();
            endtime = Tempt2.toString();
        }
        return new BorrowPrintMsg(book.getUsername(),book.getSid(),book.getBookname(),book.getBid(), book.getState(),starttime,endtime);
    }
}
